package cn.yj.syslog.filter;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * JDK 8必须要空实现 init 和 destroy 方法，否则打包无法启动
 * @author 永健
 * @since 2022-01-07 17:04
 */
public class RequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        ServletRequest requestWrapper = null;
        // 为json请求的时候，重新包装request
        if (request.getContentType() != null && request.getContentType().equals("application/json")) {
            if (request instanceof HttpServletRequest) {
                requestWrapper = new LogRequestWrapper((HttpServletRequest) request);
            }
            chain.doFilter(requestWrapper, response);
            return;
        }
        chain.doFilter(request, response);
    }
}
